package com.lalawaimai.plateform.search;

import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.lalawaimai.palteform.baselib.base.BaseActivity;
import com.lalawaimai.palteform.baselib.http.DisposeDataListener;
import com.lalawaimai.palteform.baselib.http.OkHttpException;
import com.lalawaimai.palteform.baselib.http.RequestWebInfo;
import com.lalawaimai.palteform.baselib.utils.CommonUtil;
import com.lalawaimai.palteform.baselib.utils.NullUtil;
import com.lalawaimai.plateform.R;
import com.lalawaimai.plateform.bean.OrderListBean;
import com.lalawaimai.plateform.bean.OrderListEntity;
import com.lalawaimai.plateform.bean.SearchBean;
import com.lalawaimai.plateform.bean.SearchEntity;
import com.lalawaimai.plateform.constant.Constant;
import com.lalawaimai.plateform.http.WebUrl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * 搜索页面
 * Created by WaterWood on 2018/6/2.
 */
public class SearchActivity extends BaseActivity implements View.OnClickListener, DatePickerDialog.OnDateSetListener {

    private TextView tv_title;
    private LinearLayout ll_back;
    private View status_bar;
    private LinearLayout ll_start_time;
    private LinearLayout ll_end_time;
    private boolean flag;//true:选择的是开始时间  false:选择的是结束时间
    private View contentView1;//配送员的布局
    private View contentView2;//店铺的布局
    private View contentView3;//代理的布局
    private PopupWindow popupWindowDistributor;//配送员的弹框
    private PopupWindow popupWindowStore;//店铺的弹框
    private PopupWindow popupWindowAgent;//店铺的弹框
    private LinearLayout ll_choose_distributor;
    private ProgressDialog dialogWeb;//网络加载等待框
    private SearchBean searchBean;
    private List<SearchEntity> deliveryersList;
    private List<SearchEntity> storesList;
    private List<SearchEntity> agentsList;
    private List<Boolean> deliveryersListCheck;//标记配送员是不是选中
    private List<Boolean> storesListCheck;//标记店铺是不是选中
    private List<Boolean> agentListCheck;//标记店铺是不是选中
    private int deliveryerPos = -1;//选中配送员的位置
    private int storePos = -1;//选中店铺的位置
    private int agentPos = -1;//选中代理的位置
    private boolean isDeliveryerSure;//点击的是确定
    private boolean isStoreSure;
    private boolean isAgentSure;
    private int deliveryersForePos = -1;//上次记录位置
    private int storeForePos = -1;//上次记录的位置
    private int agentForePos = -1;//上次记录的位置
    private TextView tv_deliveryer;
    private TextView tv_store;
    private LinearLayout ll_choose_store;
    private LinearLayout ll_choose_agent;
    private TextView tv_agent;
    private TextView tv_start;
    private TextView tv_end;
    private Button bt_reset;
    private EditText et_uid;
    private EditText et_keyword;
    private Button bt_search;
    private String startTime;
    private String endTime;

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_search;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void initWidget() {
        //初始化控件
        tv_title = findViewById(R.id.tv_title);
        ll_back = findViewById(R.id.ll_back);
        status_bar = findViewById(R.id.status_bar);
        ll_start_time = findViewById(R.id.ll_start_time);
        ll_end_time = findViewById(R.id.ll_end_time);
        ll_choose_distributor = findViewById(R.id.ll_choose_distributor);
        tv_deliveryer = findViewById(R.id.tv_deliveryer);
        tv_store = findViewById(R.id.tv_store);
        ll_choose_store = findViewById(R.id.ll_choose_store);
        ll_choose_agent = findViewById(R.id.ll_choose_agent);
        tv_agent = findViewById(R.id.tv_agent);
        tv_start = findViewById(R.id.tv_start);
        tv_end = findViewById(R.id.tv_end);
        bt_reset = findViewById(R.id.bt_reset);
        et_uid = findViewById(R.id.et_uid);
        et_keyword = findViewById(R.id.et_keyword);
        bt_search = findViewById(R.id.bt_search);
        //初始化点击事件
        ll_back.setOnClickListener(this);
        ll_start_time.setOnClickListener(this);
        ll_end_time.setOnClickListener(this);
        ll_choose_distributor.setOnClickListener(this);
        ll_choose_store.setOnClickListener(this);
        ll_choose_agent.setOnClickListener(this);
        bt_reset.setOnClickListener(this);
        bt_search.setOnClickListener(this);
        //其他操作
        tv_title.setText("订单搜索");
        setStatusBarSize(this, status_bar);
        dialogWeb = CommonUtil.showProgressDialog(this, "正在加载");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_back:
                finish();
                break;
            case R.id.ll_start_time:
                //下单开始时间
                flag = true;
                Calendar calendar1 = Calendar.getInstance();
                DatePickerDialog dialog1 = new DatePickerDialog(this, this, calendar1.get(Calendar.YEAR), calendar1.get(Calendar.MONTH), calendar1.get(Calendar.DAY_OF_MONTH));
                dialog1.setTitle("请选择下单开始时间");
                dialog1.show();
                break;
            case R.id.ll_end_time:
                //下单截止时间
                flag = false;
                Calendar calendar2 = Calendar.getInstance();
                DatePickerDialog dialog2 = new DatePickerDialog(this, this, calendar2.get(Calendar.YEAR), calendar2.get(Calendar.MONTH), calendar2.get(Calendar.DAY_OF_MONTH));
                dialog2.setTitle("请选择下单截止时间");
                dialog2.show();
                break;
            case R.id.ll_choose_distributor:
                if (popupWindowDistributor != null)
                    popupWindowDistributor.showAtLocation(contentView1, Gravity.BOTTOM, 0, 0);
                break;
            case R.id.ll_choose_store:
                if (popupWindowStore != null)
                    popupWindowStore.showAtLocation(contentView2, Gravity.BOTTOM, 0, 0);
                break;
            case R.id.ll_choose_agent:
                if (popupWindowAgent != null)
                    popupWindowAgent.showAtLocation(contentView3, Gravity.BOTTOM, 0, 0);
                break;
            case R.id.bt_reset:
                //重置客户UID
                et_uid.setText("");
                //重置订单号，姓名，电话
                et_keyword.setText("");
                //重置配送员
                deliveryerPos = -1;
                deliveryersForePos = -1;
                tv_deliveryer.setText("");
                //重置店铺
                storePos = -1;
                storeForePos = -1;
                tv_store.setText("");
                //重置代理
                agentPos = -1;
                agentForePos = -1;
                tv_agent.setText("");
                //重置开始和结束时间
                tv_start.setText("");
                tv_end.setText("");
                break;
            case R.id.bt_search:
                commit();
                break;
        }
    }

    @Override
    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
        if (flag) {
            String desc = String.format("%d年%d月%d日", year, month + 1, dayOfMonth);
            tv_start.setText(desc);
            startTime = year + "-" + month + 1 + "-" + dayOfMonth;
        } else {
            String desc = String.format("%d年%d月%d日", year, month + 1, dayOfMonth);
            tv_end.setText(desc);
            endTime = year + "-" + month + 1 + "-" + dayOfMonth;
        }
    }

    /**
     * 选择配送员的弹出框
     */
    private void initDeliveryersListPopwindow() {
        //加载弹出框的布局
        contentView1 = LayoutInflater.from(this).inflate(
                R.layout.pop_select_distributor, null);
        //-----------------这部分是对不同布局的处理-------------------
        //这里要对布局里面的控件进行操作，包括放置数据什么的
        LinearLayout ll_root = contentView1.findViewById(R.id.ll_root);
        deliveryersList = searchBean.getMessage().getData().getDeliveryers();
        //绘制列表
        ListView lv = contentView1.findViewById(R.id.lv);
        final SearchAdapter searchAdapter = new SearchAdapter(this, deliveryersList);
        searchAdapter.setDeliveryersListCheck(deliveryersListCheck);
        lv.setAdapter(searchAdapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                for (int i = 0; i < deliveryersListCheck.size(); i++) {
                    if (position == i) {
                        deliveryersListCheck.set(i, true);
                    } else {
                        deliveryersListCheck.set(i, false);
                    }
                }
                deliveryersForePos = deliveryerPos;
                deliveryerPos = position;//记录这次选择的位置
                searchAdapter.notifyDataSetChanged();
            }
        });
        lv.setSelector(new ColorDrawable(Color.TRANSPARENT));
        //确定取消按钮
        LinearLayout ll_cancel = contentView1.findViewById(R.id.ll_cancel);
        LinearLayout ll_confirm = contentView1.findViewById(R.id.ll_confirm);
        ll_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindowDistributor.dismiss();
            }
        });
        ll_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isDeliveryerSure = true;
                popupWindowDistributor.dismiss();
            }
        });
        //-------------------到这里结束---------------------------------
        //设置弹出框的宽度和高度
        popupWindowDistributor = new PopupWindow(contentView1,
                ViewGroup.LayoutParams.MATCH_PARENT,
                CommonUtil.getWindowHeight(this) / 2);
        popupWindowDistributor.setFocusable(true);// 取得焦点
        //注意  要是点击外部空白处弹框消息  那么必须给弹框设置一个背景色  不然是不起作用的
        popupWindowDistributor.setBackgroundDrawable(new BitmapDrawable());
        //点击外部消失
        popupWindowDistributor.setOutsideTouchable(true);
        //设置可以点击
        popupWindowDistributor.setTouchable(true);
        //进入退出的动画
        popupWindowDistributor.setAnimationStyle(R.style.mypopwindow_anim_style);
        // 按下android回退物理键 PopipWindow消失解决
        ll_root.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
                    if (popupWindowDistributor != null && popupWindowDistributor.isShowing()) {
                        popupWindowDistributor.dismiss();
                        return true;
                    }
                }
                return false;
            }
        });
        popupWindowDistributor.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                //监听弹框消失
                if (!isDeliveryerSure) {
                    deliveryerPos = deliveryersForePos;
                }
                for (int i = 0; i < deliveryersListCheck.size(); i++) {
                    deliveryersListCheck.set(i, false);
                }
                isDeliveryerSure = false;
                if (deliveryerPos != -1)
                    tv_deliveryer.setText(deliveryersList.get(deliveryerPos).getTitle());
            }
        });
    }

    @Override
    protected void intiData() {
        dialogWeb.show();
        String url = WebUrl.SEARCH_INIT;
        Class<?> clazz = SearchBean.class;
        List<String> list = new ArrayList<>();
        list.add("token");
        new RequestWebInfo(new DisposeDataListener() {
            @Override
            public void onSuccess(Object responseObj) {
                dialogWeb.dismiss();
                searchBean = (SearchBean) responseObj;
                if (!NullUtil.isListEmpty(searchBean.getMessage().getData().getDeliveryers())) {
                    //有配送员，则进行弹框初始化
                    deliveryersListCheck = new ArrayList<>();
                    for (int i = 0; i < searchBean.getMessage().getData().getDeliveryers().size(); i++) {
                        deliveryersListCheck.add(false);
                    }
                    initDeliveryersListPopwindow();
                }
                if (!NullUtil.isListEmpty(searchBean.getMessage().getData().getStores())) {
                    //有店铺
                    storesListCheck = new ArrayList<>();
                    for (int i = 0; i < searchBean.getMessage().getData().getStores().size(); i++) {
                        storesListCheck.add(false);
                    }
                    initStoresListPopwindow();
                }
                if (!NullUtil.isListEmpty(searchBean.getMessage().getData().getAgents())) {
                    //有店铺
                    agentListCheck = new ArrayList<>();
                    for (int i = 0; i < searchBean.getMessage().getData().getStores().size(); i++) {
                        agentListCheck.add(false);
                    }
                    initAgentListPopwindow();
                }
            }

            @Override
            public void onFailure(Object reasonObj) {
                dialogWeb.dismiss();
                OkHttpException okHttpException = (OkHttpException) reasonObj;
                String msg = okHttpException.getEmsg().toString();
                if (msg.contains("java.net.ConnectException")) {
                    CommonUtil.showToast(SearchActivity.this, "无法连接服务器，请检查您的网络");
                }
            }
        }).requestWeb(url, clazz, list,(String) CommonUtil.readData(this, Constant.TOKEN,Constant.STRING));
    }

    /**
     * 选择店铺的弹出框
     */
    private void initStoresListPopwindow() {
        //加载弹出框的布局
        contentView2 = LayoutInflater.from(this).inflate(
                R.layout.pop_select_distributor, null);
        //-----------------这部分是对不同布局的处理-------------------
        //这里要对布局里面的控件进行操作，包括放置数据什么的
        LinearLayout ll_root = contentView2.findViewById(R.id.ll_root);
        storesList = searchBean.getMessage().getData().getStores();
        //绘制列表
        ListView lv = contentView2.findViewById(R.id.lv);
        final SearchAdapter searchAdapter = new SearchAdapter(this, storesList);
        searchAdapter.setDeliveryersListCheck(storesListCheck);
        lv.setAdapter(searchAdapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                for (int i = 0; i < storesListCheck.size(); i++) {
                    if (position == i) {
                        storesListCheck.set(i, true);
                    } else {
                        storesListCheck.set(i, false);
                    }
                }
                storeForePos = storePos;
                storePos = position;//记录这次选择的位置
                searchAdapter.notifyDataSetChanged();
            }
        });
        lv.setSelector(new ColorDrawable(Color.TRANSPARENT));
        //确定取消按钮
        LinearLayout ll_cancel = contentView2.findViewById(R.id.ll_cancel);
        LinearLayout ll_confirm = contentView2.findViewById(R.id.ll_confirm);
        ll_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindowStore.dismiss();
            }
        });
        ll_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isStoreSure = true;
                popupWindowStore.dismiss();
            }
        });
        //-------------------到这里结束---------------------------------
        //设置弹出框的宽度和高度
        popupWindowStore = new PopupWindow(contentView2,
                ViewGroup.LayoutParams.MATCH_PARENT,
                CommonUtil.getWindowHeight(this) / 2);
        popupWindowStore.setFocusable(true);// 取得焦点
        //注意  要是点击外部空白处弹框消息  那么必须给弹框设置一个背景色  不然是不起作用的
        popupWindowStore.setBackgroundDrawable(new BitmapDrawable());
        //点击外部消失
        popupWindowStore.setOutsideTouchable(true);
        //设置可以点击
        popupWindowStore.setTouchable(true);
        //进入退出的动画
        popupWindowStore.setAnimationStyle(R.style.mypopwindow_anim_style);
        // 按下android回退物理键 PopipWindow消失解决
        ll_root.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
                    if (popupWindowStore != null && popupWindowStore.isShowing()) {
                        popupWindowStore.dismiss();
                        return true;
                    }
                }
                return false;
            }
        });
        popupWindowStore.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                //监听弹框消失
                if (!isStoreSure) {
                    storePos = storeForePos;
                }
                for (int i = 0; i < storesListCheck.size(); i++) {
                    storesListCheck.set(i, false);
                }
                isStoreSure = false;
                if (storePos != -1)
                    tv_store.setText(storesList.get(storePos).getTitle());
            }
        });
    }

    /**
     * 选择代理的弹出框
     */
    private void initAgentListPopwindow() {
        //加载弹出框的布局
        contentView3 = LayoutInflater.from(this).inflate(
                R.layout.pop_select_distributor, null);
        //-----------------这部分是对不同布局的处理-------------------
        //这里要对布局里面的控件进行操作，包括放置数据什么的
        LinearLayout ll_root = contentView3.findViewById(R.id.ll_root);
        agentsList = searchBean.getMessage().getData().getAgents();
        //绘制列表
        ListView lv = contentView3.findViewById(R.id.lv);
        final SearchAdapter searchAdapter = new SearchAdapter(this, agentsList);
        searchAdapter.setDeliveryersListCheck(agentListCheck);
        lv.setAdapter(searchAdapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                for (int i = 0; i < agentListCheck.size(); i++) {
                    if (position == i) {
                        agentListCheck.set(i, true);
                    } else {
                        agentListCheck.set(i, false);
                    }
                }
                agentForePos = agentPos;
                agentPos = position;//记录这次选择的位置
                searchAdapter.notifyDataSetChanged();
            }
        });
        lv.setSelector(new ColorDrawable(Color.TRANSPARENT));
        //确定取消按钮
        LinearLayout ll_cancel = contentView3.findViewById(R.id.ll_cancel);
        LinearLayout ll_confirm = contentView3.findViewById(R.id.ll_confirm);
        ll_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindowAgent.dismiss();
            }
        });
        ll_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isAgentSure = true;
                popupWindowAgent.dismiss();
            }
        });
        //-------------------到这里结束---------------------------------
        //设置弹出框的宽度和高度
        popupWindowAgent = new PopupWindow(contentView3,
                ViewGroup.LayoutParams.MATCH_PARENT,
                CommonUtil.getWindowHeight(this) / 2);
        popupWindowAgent.setFocusable(true);// 取得焦点
        //注意  要是点击外部空白处弹框消息  那么必须给弹框设置一个背景色  不然是不起作用的
        popupWindowAgent.setBackgroundDrawable(new BitmapDrawable());
        //点击外部消失
        popupWindowAgent.setOutsideTouchable(true);
        //设置可以点击
        popupWindowAgent.setTouchable(true);
        //进入退出的动画
        popupWindowAgent.setAnimationStyle(R.style.mypopwindow_anim_style);
        // 按下android回退物理键 PopipWindow消失解决
        ll_root.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
                    if (popupWindowAgent != null && popupWindowAgent.isShowing()) {
                        popupWindowAgent.dismiss();
                        return true;
                    }
                }
                return false;
            }
        });
        popupWindowAgent.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                //监听弹框消失
                if (!isAgentSure) {
                    agentPos = agentForePos;
                }
                for (int i = 0; i < agentListCheck.size(); i++) {
                    agentListCheck.set(i, false);
                }
                isAgentSure = false;
                if (agentPos != -1)
                    tv_agent.setText(agentsList.get(agentPos).getTitle());
            }
        });
    }

    /**
     * 提交搜索
     */
    private void commit() {
        if (checkEmpty()) {
            Intent intent = new Intent(this, SearchResultActivity.class);
            intent.putExtra("uid", et_uid.getText().toString().trim());
            intent.putExtra("keyword", et_keyword.getText().toString().trim());
            if (!NullUtil.isListEmpty(deliveryersList) && deliveryerPos != -1) {
                intent.putExtra("deliveryer_id", deliveryersList.get(deliveryerPos).getId());
            }
            if (!NullUtil.isListEmpty(storesList) && storePos != -1) {
                intent.putExtra("sid", storesList.get(storePos).getId());
            }
            if (!NullUtil.isListEmpty(agentsList) && agentPos != -1) {
                intent.putExtra("agentid", agentsList.get(agentPos).getId());
            }
            intent.putExtra("addtime_start", startTime);
            intent.putExtra("addtime_end", endTime);
            startActivity(intent);
        }else{
            CommonUtil.showToast(this,"请输入搜索条件");
        }
    }

    private boolean checkEmpty() {
        if (NullUtil.isStringEmpty(et_uid.getText().toString().trim())) {
            if (NullUtil.isStringEmpty(et_keyword.getText().toString().trim())) {
                if (deliveryerPos == -1) {
                    if (storePos == -1) {
                        if (agentPos == -1) {
                            if (NullUtil.isStringEmpty(startTime)) {
                                if (NullUtil.isStringEmpty(endTime)) {
                                    return false;
                                }
                            }
                        }
                    }
                }
            }
        }
        return true;
    }
}
